/**
 * Created by qunxing.du on 2016/8/11.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.pollution.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 污染源采集服务器入口
 */
public class Server {
    private static Logger log = Logger.getLogger(Server.class);

    private int port = 30003;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    public void init(int port){
        this.port = port;
        log.info("启动污染源服务端。。。");
        start();
    }

    private void start (){
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new CustomChannelInitializer());
            ChannelFuture f = serverBootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
            log.info("启动污染源服务端成功，端口:"+this.port);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e);
        } finally {
            destory();
        }
    }

    public void destory(){
        log.info("关闭污染源服务端。。。");
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        log.info("关闭污染源服务端成功");
    }
}
